﻿//data members
var currentShape    = null;
var dragShape       = null;
var icon            = '<img alt="" src="img/beer-icon.ico"  style="display:block; height: 30px; width: 30px;" />';
var starRatingsList = "<li class='current-rating' style='width:##REPLACE##px;'> Currently 3.5/5 Stars.</li><li><a href='#' title='1 star out of 5' class='one-star' onclick='updateRating(\"1\");'>1</a></li><li><a href='#' title='2 stars out of 5' class='two-stars' onclick='updateRating(\"2\");'>2</a></li><li><a href='#' title='3 stars out of 5' class='three-stars' onclick='updateRating(\"3\");'>3</a></li><li><a href='#' title='4 stars out of 5' class='four-stars' onclick='updateRating(\"4\");'>4</a></li><li><a href='#' title='5 stars out of 5' class='five-stars' onclick='updateRating(\"5\");'>5</a></li>";
var editMode        = false;

function startUp() {
    GetMap();
    //add custom fields to VEShape
    VEShape.prototype.SetRating = function (newRating) {
        this.rating = newRating;
    };

    VEShape.prototype.GetRating = function () {
        return this.rating;
    };

    VEShape.prototype.SetReview = function (newReview) {
        this.review = newReview;
    };

    VEShape.prototype.GetReview = function () {
        return this.review;
    };

    VEShape.prototype.SetUID = function (uid) {
        this.uID = uid;
    };

    VEShape.prototype.GetUID = function () {
        return this.uID;
    };

    //create jquery outerHTML
    $.fn.outerHTML = function (s) {
        return (s) ? this.before(s).remove() : $("<div>").append(this.eq(0).clone()).html();
    }

    //set default zoom level to 7
    updateZoom(7);
}

function updateRating(rating) {
    if (editMode) {
        $("#rating").val(rating);
        $(".current-rating").width(rating * 25 + "px");
    }
}
// *******************************************************
// event handler to resize the map when the window resizes
function resizeMap() {
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        map.Resize(window.innerWidth, window.innerHeight);
    }
    else if (document.documentElement && (document.documentElement.clientWidth
       || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        map.Resize(document.documentElement.clientWidth, document.documentElement.clientHeight);
    }
}

function updateZoom(zoomLevel) {
    var zoomCombo = $("#zoomLevel");
    zoomCombo.html("");
    //add zoom levels to map
    for (var i = 1; i <= 20; i++) {
        var option = $("<option>").attr("value", i).html(i);
        if (i == zoomLevel) option.attr("selected", "selected");
        option.appendTo(zoomCombo);
    }
    map.SetZoomLevel(zoomLevel);
}

// ***************************************************************
// event handler to allow the current pushpin to be dragged around
function MouseHandler(e) {
    var msg;
    if (e.eventName == "onmousedown" && e.elementID != null) {
        dragShape = map.GetShapeByID(e.elementID);
        return true; // prevent the default action
    }
    else if (e.eventName == "onmouseup") {
        if (dragShape != null) {
            var xLat = dragShape.Latitude;
            var xLong = dragShape.Longitude;
        }
        dragShape = null;
        if( xLat != null )
            updateLatLong(e.elementID);
    }
    else if (e.eventName == "onmousemove" && dragShape != null) {
        var x = e.mapX;
        var y = e.mapY;
        pixel = new VEPixel(x, y);
        var LL = map.PixelToLatLong(pixel);
        dragShape.SetPoints(LL);
        return true; // prevent the default action
    } else if (e.eventName == "ondoubleclick") {
        editMode = true;
        currentShape = map.GetShapeByID(e.elementID);
        var updateFunction = "updatePin('" + e.elementID + "')";

        var txtTitle = $(document.createElement('input')).attr("id", 'txtTitle').attr("value", $(".VE_Pushpin_Popup_Title").html());
        $(".VE_Pushpin_Popup_Title").html("");
        txtTitle.appendTo(".VE_Pushpin_Popup_Title");

        var description = currentShape.GetReview() != undefined ? currentShape.GetReview() : "Enter Your Review";
        var txtDescription = $(document.createElement('input')).attr("id", 'txtDescription').attr("value", description);
        $(".VE_Pushpin_Popup_Body").html("");
        txtDescription.appendTo(".VE_Pushpin_Popup_Body");

        $("#rating").val(currentShape.GetRating());
        var ulRating = $(document.createElement('ul')).attr("class", "star-rating").html(starRatingsList.replace("##REPLACE##", 25 * currentShape.GetRating()));
        ulRating.appendTo(".VE_Pushpin_Popup_Body");

        var updateLink = $(document.createElement('input')).attr("type", "button").attr("id", "btnUpdate").attr("onClick", updateFunction ).attr("value", "Update");
        updateLink.appendTo(".VE_Pushpin_Popup_Body");

        return true;
    }
}


// ***************************
// AJAX error handler function
function errorHandler(error) {
    alert(error.get_message());
}

// ****************************************************
// function adds a new pushpin at the centre of the map
function insertPin() {
    shape = new VEShape(VEShapeType.Pushpin, map.GetCenter());
    shape.SetTitle("Double Click To Edit Title");
    shape.SetReview("Enter your review here" );
    shape.SetDescription(shape.GetReview() + " " + $(document.createElement('ul')).attr("class", "star-rating").html(starRatingsList.replace("##REPLACE##", 25 * 1)).outerHTML());
    shape.SetCustomIcon(icon);
    shape.SetRating("1");

    map.AddShape(shape);
    currentShape = shape;

    //call server method to save to xml
    SaveData(shape.GetUID() + "~" + shape.Title + "~" + shape.GetReview() + "~" + shape.GetRating() + "~" + shape.Latitude + "~" + shape.Longitude);

}

function updatePin(eID) {
    updateShape = map.GetShapeByID(eID);
    updateShape.SetTitle($('#txtTitle').val());
    updateShape.SetReview($('#txtDescription').val());
    updateShape.SetRating($('#rating').val());
    updateShape.SetDescription(updateShape.GetReview() + " " + $(document.createElement('ul')).attr("class", "star-rating").html(starRatingsList.replace("##REPLACE##", 25 * updateShape.GetRating() )).outerHTML());
    

    //call server method to save to xml
    UpdateData( updateShape.GetUID() + "~" + updateShape.Title + "~" + updateShape.GetReview() + "~" + updateShape.GetRating() + "~" + updateShape.Latitude + "~" + updateShape.Longitude );
}

function updateLatLong(eID) {
    updateShape = map.GetShapeByID(eID);
    //call server method to save to xml
    SaveData(updateShape.GetUID() + "~" + updateShape.Title + "~" + updateShape.GetReview() + "~" + updateShape.GetRating() + "~" + updateShape.Latitude + "~" + updateShape.Longitude);
}

// Update current pin to server xml
function UpdateData( data ) {
    PageMethods.SavePushPin(data, finishUpdateData, errorHandler);
}

// Save current pin to server xml
function SaveData( data ) {
    PageMethods.SavePushPin( data, finishSaveData, errorHandler);
}

//get all pins in xml sheet
function GetPins( ) {
    PageMethods.GetPinCollection( finishPinCollection, errorHandler );
}

// **********************
// AJAX callback function
function finishSaveData(response) {
    if (currentShape != undefined)
        currentShape.SetUID(response); //set shape to new return ID
}

function finishUpdateData(response) {
    if (currentShape != undefined)
        currentShape.SetUID(response); //set shape to new return ID
    if (response >= 0)
        alert('Update Successful');
    editMode = false;
}

function finishPinCollection(pinCollection) {
    //deleteAllShapes();

    if (pinCollection == "zero") {
        alert("No pubs found");
        return;
    }

    var retArray = pinCollection.split("|");

    for (var i = 0; i < retArray.length; i++) {
        var pinData = retArray[i].split('~');

        var pinLat = pinData[4];
        var pinLong = pinData[5];
        var pinLatLong = new VELatLong( 0, 0 );

        if (pinLat != "" && pinLong != "") {
            pinLatLong = new VELatLong(pinLat, pinLong);
            if (i == 0) {
                updateZoom(16);
                map.SetCenterAndZoom(pinLatLong, 16);
            }
        }

        shape = new VEShape(VEShapeType.Pushpin, pinLatLong);
        shape.SetUID(pinData[0]);
        shape.SetTitle(pinData[1]);
        shape.SetReview(pinData[2]);
        var ratingList = $(document.createElement('ul')).attr("class", "star-rating").html(starRatingsList.replace("##REPLACE##", 25 * pinData[3]));
        shape.SetDescription(shape.GetReview() + " " + ratingList.outerHTML());
        shape.SetRating( pinData[3]) ;
        shape.SetCustomIcon( icon );

        map.AddShape(shape);
    }

    updateZoom(zFact);
    map.SetCenterAndZoom(pinLatLong, zFact);
}